package mf.com.Service.impl.Product;

import com.alibaba.excel.EasyExcel;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import mf.com.Service.Product.CategoryService;
import mf.com.entity.product.Category;
import mf.com.listener.ExcelListener;
import mf.com.mapper.product.ProductCategoryMapper;
import mf.com.uilts.TreeBuilder;
import mf.com.vo.common.Result;
import mf.com.vo.product.CategoryExcelVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author: lmf
 * @Create: 2024/3/31 15:11
 * Description:  分类管理服务层
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private ProductCategoryMapper productCategoryMapper;

    @Override
    public List<Category> findById(Long level) {
        if(level == 0) {
            return findMainAll();
        }
        return productCategoryMapper.findById(level);
    }

    /**
     * 导入
     * @param file 上传的文件流
     */
    @Override
    public void importData(MultipartFile file) {
        final ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>(productCategoryMapper);
         try {
             EasyExcel.read(file.getInputStream(),CategoryExcelVo.class,excelListener)
                     .sheet().doRead();
         }  catch (IOException e) {
             throw new RuntimeException(e);
         }
    }

    /**
     * 导出所有数据
     */
    @Override
    public void exportData(HttpServletResponse response) {
        // 设置响应头信息和其他信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 防止乱码
        final String fileName = URLEncoder.encode("分类数据", StandardCharsets.UTF_8);

         try {
             // 设置响应头信息
             // 以下载方式打开
             response.setHeader("Content-disposition",
                     "attachment;filename=" + fileName+".xlsx");

             // 获取所有分类数据
             final List<Category> categoryList = productCategoryMapper.selectAll();

             // 类型装换
             final ArrayList<CategoryExcelVo> voArrayList = new ArrayList<>();

             // 将类型 category 值 复制到  excelVo 中去，完成类型转换
             for (Category category : categoryList) {
                 final CategoryExcelVo excelVo = new CategoryExcelVo();
                 BeanUtils.copyProperties(category, excelVo);
                 voArrayList.add(excelVo);
             }


             // 调用 easyExcel 的 write方法完成写操作
             EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                     .sheet("分类数据")
                     .doWrite(voArrayList);
         } catch (IOException e) {
             throw new RuntimeException(e);
         }

    }

    /**
     * 所有分类信息第一层信息
     */
    @Override
    public List<Category> findMainAll() {
        final List<Category> categoryList = productCategoryMapper.selectAll();
         List<Category> categoryList1 = TreeBuilder.buildTree(categoryList);

        setLeafNodeHasChildren(categoryList1);
        return categoryList1;
    }

    /**
     * 设置树中所有叶节点的HasChildren字段为false。
     *
     * @param tree 要处理的树
     */
    public void setLeafNodeHasChildren(List<Category> tree) {
        for (Category node : tree) {
            if (node.getChildren() == null) {
                // 如果节点是叶节点，并且它实现了HasChildren接口，则设置其hasChildren字段为false
                node.setHasChildren(false);
            } else {
                node.setHasChildren(true);
                // 如果节点有子节点，则递归处理其子节点
                setLeafNodeHasChildren(node.getChildren());
            }
        }
    }

    /**
     * 根据 id 查询 子分类
     */
    @Override
    public List<Category> findSubcategory(Long id) {
        final List<Category> subCategory = productCategoryMapper.findSubCategory(id);
        System.out.println(subCategory);
        return subCategory;
    }


}
